﻿using MongoDB.Driver;
using NLog;
using OPCService.Model;
using OPCService.Service;
using OPCService.Utils;
using Quartz;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace OPCService.Job
{
    class RemoveHistoryData: IJob
    {
        private static readonly Logger logger = NLog.LogManager.GetCurrentClassLogger();
        private static readonly String colName = ConfigHelper.ReadConfig("colname");
        private static MongoDbHelper mongoDbHelper = new MongoDbHelper();

        #region 入口
        public async Task Execute(IJobExecutionContext context)
        {
            await Task.Run(async () =>
            {
                try
                {
                    await deleteMany();
                    //await httpExample();
                    //await sqliteExample();
                    //await modbusExample();
                    //await serialExample();
                }
                catch (Exception e)
                {
                    logger.Error(e.Message);
                }
            });
        }
        #endregion

        private async Task<List<Item>> findByFilter()
        {
            // 创建构建器
            var builder = Builders<Item>.Filter;

            // 单条件查询
            var timeBefore = DateTime.UtcNow.AddHours(-1);
            FilterDefinition<Item> filter = builder.Lt("datetime", timeBefore);

            List<Item> datalist = mongoDbHelper.find<Item>(colName, filter);
            return datalist;
        }

        private async Task deleteMany()
        {
            // 创建构建器
            var builder = Builders<Item>.Filter;

            // 单条件查询
            var timeBefore = DateTime.UtcNow.AddHours(-1);
            FilterDefinition<Item> filter = builder.Lt("datetime", timeBefore);

            mongoDbHelper.deleteMany(colName, filter);
        }

        private async Task httpExample()
        {
            string baseUrl = "http://10.99.100.128:8020/jeecg-boot/";
            HttpService httpService = new HttpService(baseUrl);

            // 定义查询参数
            var queryParams = new Dictionary<string, string>
            {
                { "id", "1929462725927763970" }
            };
            string path = "factory/wmModal/queryById";
            var response = await httpService.GetAsync<ApiResponse<WmModel>>(path, queryParams);
            Console.WriteLine($"=======Response: {response.code}");

            //string json = JsonSerializer.Serialize(response, new JsonSerializerOptions { WriteIndented = true });
            /*string path2 = "factory/wmModal/list";
            var response2 = await httpService.GetAsync<ApiResponse<Records>>(path2);
            Console.WriteLine($"=======Response2: {response2.code}");*/


            /*var newWmModel = new WmModel
            {
                factory = "",
                device = "New Todo Item",
                thumbnail = ""
            };

            // 发送 POST 请求
            var response2 = await httpService.PostAsync<ApiResponse<null>>("/factory/wmModal/add", newWmModel);
            Console.WriteLine($"Create response: {response2}");*/
        }

        private async Task sqliteExample()
        {
            // 创建数据库实例
            using (var db = new SQLiteService("MyDatabase.sqlite"))
            {
                /**
                 * 示例1  基本使用
                 */
                // 创建表
                db.CreateTableIfNotExists("Users",
                    "Id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                    "Name TEXT NOT NULL, " +
                    "Email TEXT UNIQUE, " +
                    "Age INTEGER, " +
                    "CreatedAt DATETIME DEFAULT CURRENT_TIMESTAMP");

                // 插入数据
                var userData = new Dictionary<string, object>
                {
                    { "Name", "张三" },
                    { "Email", "zhangsan@example.com" },
                    { "Age", 30 }
                };
                //long userId = db.Insert("Users", userData);

                // 查询数据
                var query = "SELECT * FROM Users WHERE Age > @age";
                var parameters = new Dictionary<string, object> { 
                    { "@age", 25 } 
                };
                DataTable result = db.ExecuteQuery(query, parameters);

                // 输出结果
                foreach (DataRow row in result.Rows)
                {
                    Console.WriteLine($"ID: {row["Id"]}, 姓名: {row["Name"]}, 年龄: {row["Age"]}");
                }

                // 更新数据
                var updateData = new Dictionary<string, object> { 
                    { "Age", 31 } 
                };
                //int updated = db.Update("Users", updateData, "Id = @id", new Dictionary<string, object> { { "@id", userId } });

                // 删除数据
                //int deleted = db.Delete("Users", "Id = @id", new Dictionary<string, object> { { "@id", userId } });


                /**
                 * 示例2 高级功能
                 */
                // 创建产品表
                /*db.CreateTableIfNotExists("Products",
                    "Id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                    "Name TEXT NOT NULL, " +
                    "Price REAL NOT NULL, " +
                    "Stock INTEGER DEFAULT 0, " +
                    "Category TEXT");

                // 批量插入产品
                var products = new List<Dictionary<string, object>>
                {
                    new Dictionary<string, object> { { "Name", "笔记本电脑" }, { "Price", 5999.99 }, { "Stock", 10 }, { "Category", "电子产品" } },
                    new Dictionary<string, object> { { "Name", "智能手机" }, { "Price", 3999.50 }, { "Stock", 20 }, { "Category", "电子产品" } },
                    new Dictionary<string, object> { { "Name", "平板电脑" }, { "Price", 2999.00 }, { "Stock", 15 }, { "Category", "电子产品" } }
                };

                foreach (var product in products)
                {
                    db.Insert("Products", product);
                }

                // 执行复杂查询
                string complexQuery = @"
                        SELECT Category, COUNT(*) AS ProductCount, AVG(Price) AS AvgPrice
                        FROM Products
                        WHERE Stock > 0
                        GROUP BY Category
                        HAVING AVG(Price) > @minPrice";

                var queryParams = new Dictionary<string, object> { { "@minPrice", 3000 } };
                DataTable report = db.ExecuteQuery(complexQuery, queryParams);

                // 输出报告
                Console.WriteLine("类别\t产品数量\t平均价格");
                foreach (DataRow row in report.Rows)
                {
                    Console.WriteLine($"{row["Category"]}\t{row["ProductCount"]}\t{row["AvgPrice"]:C}");
                }

                // 备份数据库
                db.BackupDatabase("Products_Backup.sqlite");*/


                /**
                 * 示例3 使用事务
                 */
                /*db.CreateTableIfNotExists("Orders",
                    "Id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                    "CustomerId INTEGER, " +
                    "Amount REAL, " +
                    "OrderDate DATETIME DEFAULT CURRENT_TIMESTAMP");

                db.CreateTableIfNotExists("OrderItems",
                    "Id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                    "OrderId INTEGER, " +
                    "ProductId INTEGER, " +
                    "Quantity INTEGER, " +
                    "Price REAL");

                // 执行事务
                var transactionActions = new List<Action<SQLiteCommand>>
                {
                    cmd =>
                    {
                        cmd.CommandText = "INSERT INTO Orders (CustomerId, Amount) VALUES (1, 100.0)";
                        cmd.ExecuteNonQuery();
                    },
                    cmd =>
                    {
                        cmd.CommandText = "SELECT last_insert_rowid()";
                        long orderId = (long)cmd.ExecuteScalar();

                        cmd.CommandText = "INSERT INTO OrderItems (OrderId, ProductId, Quantity, Price) " +
                                          "VALUES (@orderId, 101, 2, 50.0)";
                        cmd.Parameters.AddWithValue("@orderId", orderId);
                        cmd.ExecuteNonQuery();
                    }
                };

                db.ExecuteTransaction(transactionActions);*/
            }
        }

        private async Task modbusExample()
        {
            using (var client = new ModbusTcpClient("127.0.0.1", 502))
            {
                // 注册日志事件
                client.OnLog += (sender, message) => Console.WriteLine($"[LOG] {message}");

                // 同步连接
                if (client.Connect())
                {
                    // 读取保持寄存器
                    int[] registers = client.ReadHoldingRegisters(0, 10);
                    if (registers != null)
                    {
                        Console.WriteLine("读取到寄存器值:");
                        for (int i = 0; i < registers.Length; i++)
                        {
                            Console.WriteLine($"寄存器 {i}: {registers[i]}");
                        }
                    }

                    // 写入浮点数
                    bool writeFloatResult = client.WriteFloatToRegisters(5, 3.1415926f); //每个 Modbus 寄存器只能存储 16 位整数，一个 32 位浮点数（float）需要 4 字节，因此必须用 2 个寄存器 来存储（位置5和6），第一个寄存器存储高 16 位（高位字），第二个寄存器存储低 16 位（低位字）
                    Console.WriteLine($"写入浮点数结果: {writeFloatResult}");

                    //读取浮点数
                    float value = client.ReadFloatFromRegisters(5);  // 从地址 5 和 6 读取
                    Console.WriteLine($"读取浮点数: {value}");

                    // 写入字符串
                    //bool writeStringResult = client.WriteStringToRegisters(10, "Hello Modbus");
                    //Console.WriteLine($"写入字符串结果: {writeStringResult}");

                    // 异步写入
                    bool asyncWriteResult = await client.WriteSingleRegisterAsync(9, 42);
                    Console.WriteLine($"异步写入结果: {asyncWriteResult}");

                    // 断开连接
                    client.Dispose();
                }
            }
        }

        private async Task serialExample()
        {
            using (var serialPort = new SerialPortClient("COM7"))
            {
                serialPort.BaudRate = 115200;
                serialPort.DataEndDelimiter = "\n"; // 自定义数据结束符

                // 注册事件
                serialPort.DataReceived += (sender, data) =>
                {
                    Console.WriteLine($"[收到数据] {data}");
                };

                serialPort.ConnectionStatusChanged += (sender, isOpen) =>
                {
                    Console.WriteLine($"[连接状态] {(isOpen ? "已连接" : "已断开")}");
                };

                serialPort.ErrorOccurred += (sender, ex) =>
                {
                    Console.WriteLine($"[错误] {ex.Message}");
                };

                // 打开串口
                serialPort.Open();

                // 发送数据
                serialPort.Write("Hello, Serial Port!\n");
                serialPort.Dispose();
            }
        }
    }
}
